<?php


namespace app\admin\controller;


use think\Controller;
use think\Db;
use think\Request;

class Banner extends Controller
{
    public function index()
    {

        return $this->fetch();
    }

    public function queryBanner()
    {
        if($this->request->isAjax()){
            $data = Db::table('hisi_cms_banner')
                ->where('status',5)
                ->page(1)
                ->limit(15)
                ->select();
            return json(["code" => 0,"data"=>$data]);
        }
    }

    public function add()
    {
        return $this->fetch();
    }

    public function add_banner(Request $request)
    {
        //接收
        $data = $request->post();
        $articleData = [
            "title" => $data["title"],
            "image" => $data["image"],
            "url" => $data["url"],
            'create_time' => time()
        ];
        $result = Db::table('hisi_cms_banner')->insert($articleData);
        if ($result === 1) {
            $this->success("增加成功",url("admin/banner/index"),"",1);
        } else {
            $this->error("增加失败",url("admin/banner/add"),"",1);
        }
    }

    public function deleteBanner(Request $request)
    {
        $id = $request->param('id');
        $result = Db::table('hisi_cms_banner')->where('id',$id)->delete();
        if ($result === 1){
            return json(['code'=>1,'msg'=>"删除成功"]);
        }
    }

    public function edit(Request $request)
    {
        $id = $request->param('id');
        $data = Db::table('hisi_cms_banner')->where('id',$id)->find();
        $this->assign("data",$data);
        return $this->fetch();
    }

    public function save_banner(Request $request)
    {
        $data = $request->post();
        $articleData = [
            "title" => $data["title"],
            "image" => $data["image"],
            "url" => $data["url"],
        ];
        $result = Db::table("hisi_cms_banner")->where('id',$data['id'])->update($articleData);
        if ($result === 1) {
            $this->success("修改成功",url("admin/banner/index"),"",1);
        } else {
            $this->error("修改失败",url("admin/banner/index"),"",1);
        }
    }

    public function upload()
    {
        if (isset($_FILES["file"])) {
            $file = $_FILES["file"];
            $server = $_SERVER;
            $path =  dirname(dirname(dirname(__DIR__))).DIRECTORY_SEPARATOR .'public'. DIRECTORY_SEPARATOR . 'uploads'.DIRECTORY_SEPARATOR;
            $filename = time() . '.png';
            move_uploaded_file($file["tmp_name"],$path.$filename);
        }
        return json_encode(["code"=>0,"msg"=>"上传成功","file"=> $server["REQUEST_SCHEME"] . '://' . $server["SERVER_NAME"] . '/uploads/' . $filename]);
    }
}